/*
 Copyright (c) 2010, Advanced Micro Devices
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without modification, are permitted 
 provided that the following conditions are met:
 
 Redistributions of source code must retain the above copyright notice, this list of conditions 
 and the following disclaimer.
 
 Redistributions in binary form must reproduce the above copyright notice, this list of 
 conditions and the following disclaimer in the documentation and/or other materials provided 
 with the distribution.
 
 Neither the name of Advanced Micro Devices nor the names of its contributors may be used to endorse 
 or promote products derived from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 POSSIBILITY OF SUCH DAMAGE.
 */

#include <QtGui>
#include <QStringList>
#include <QDebug>

#include "stage.h"
#include "kernel.h"
#include "stagePropertiesDialog.h"
#include "EditorWindow.h"

#define PARAMETER( i ) param##i
#define ARGUMENT( i ) arg##i

StagePropertiesDialog::StagePropertiesDialog( Stage * stage, EditorWindow * window, QWidget * parent )
    : QDialog(parent)
{
	setupUi( this );
    stageIs( stage );
	stage->windowIs( window );
	enlistWidgets();
	name->setText( stage->name() );
	type->setCurrentIndex( type->findText( stage->type_() ));
	selectorCount->setValue( stage->selectorCount() );
	globalDimensions->setValue( stage->globalDimensions() );
	globalRange->setText( stage->globalRange() );
	localDimensions->setValue( stage->localDimensions() );
	localRange->setText( stage->localRange() );
	barrier->setText( stage->barrier() );
	QStringList keys = window->kernels().keys();
	kernel->insertItems( 0, keys );
	if( type->currentText().compare( "kernel" ) == 0 && stage->kernel() != NULL ){
		int index = kernel->findText( stage->kernel()->name() );
		kernel->setCurrentIndex( index );
	}
	updateKernelSignature( "" );
	connect( kernel, SIGNAL( currentIndexChanged( const QString & )),
		this, SLOT( updateKernelSignature( const QString & )));
}

#if 0
StagePropertiesDialog::~StagePropertiesDialog()
{
	
}
#endif

void StagePropertiesDialog::updateKernelSignature( const QString & string )
{
	setKernelParameters();
	setStageArguments();
}

void StagePropertiesDialog::setKernelParameters()
{
	if( stage()->window()->kernels().count() == 0 ){
		return;
	}
	QString kernelName = kernel->currentText();
	Kernel * selectedKernel = stage()->window()->kernels().value( kernelName );
	for( int i = 0; i < selectedKernel->numParameters(); ++i ){
		QString parameterName = selectedKernel->parameter()[ i + 1 ];
		mParameter[ i ]->setText( parameterName );
	}//for
	for( int i = selectedKernel->numParameters(); i < MAX_KERNEL_PARAMETERS; ++i ){
		mParameter[ i ]->setText( "" );
	}//for
}


void StagePropertiesDialog::setStageArguments()
{
	if( stage()->window()->kernels().count() == 0 ){
		return;
	}
	QString kernelName = kernel->currentText();
	Kernel * selectedKernel = stage()->window()->kernels().value( kernelName );
	for( int i = 1; i <= selectedKernel->numParameters(); ++i ){
		QString storageClass = selectedKernel->storageClass()[ i ];
		QString dataType = selectedKernel->dataType()[ i ];
		QComboBox * argument = mArgument[ i - 1 ];
		argument->insertItem( 0, "" );
		if( storageClass.compare( "" ) == 0 ){
			// uniform
			foreach( Uniform * uniform, stage()->window()->uniforms() ){
				if( uniform->dataType().compare( dataType ) == 0 ){
					argument->insertItem( argument->count(), uniform->name() );
				}
			}//foreach
		}
		else{
			// buffer
			foreach( Buffer * buffer, stage()->window()->buffers() ){
				if( buffer->storageClass().compare( storageClass ) == 0 &&
					buffer->dataType().compare( dataType ) == 0 ){
						argument->insertItem( argument->count(), buffer->name() );
				}
			}//foreach
		}
		if( stage()->arguments().size() >= i && stage()->arguments()[ i - 1 ].compare( "" ) ){
			argument->setCurrentIndex( argument->findText( stage()->arguments()[ i - 1 ] ));
		}
	}//for
	for( int i = selectedKernel->numParameters() + 1; i <= MAX_KERNEL_PARAMETERS; ++i ){
		mArgument[ i - 1 ]->clear();
	}//for
}

void StagePropertiesDialog::enlistWidgets()
{
#define PM( i ) mParameter.insert( MAX_KERNEL_PARAMETERS, PARAMETER( i ))
	PM( 0 ); PM( 1 ); PM( 2 ); PM( 3 ); PM( 4 ); PM( 5 ); 
	PM( 6 ); PM( 7 ); PM( 8 ); PM( 9 ); PM( 10 ); PM( 11 );
	PM( 12 ); PM( 13 ); PM( 14 ); PM( 15 ); PM( 16 ); PM( 17 );
	PM( 18 ); PM( 19 ); PM( 20 ); PM( 21 ); PM( 22 ); PM( 23 );
#define AR( i ) mArgument.insert( MAX_KERNEL_PARAMETERS, ARGUMENT( i ))
	AR( 0 ); AR( 1 ); AR( 2 ); AR( 3 ); AR( 4 ); AR( 5 ); 
	AR( 6 ); AR( 7 ); AR( 8 ); AR( 9 ); AR( 10 ); AR( 11 );
	AR( 12 ); AR( 13 ); AR( 14 ); AR( 15 ); AR( 16 ); AR( 17 );
	AR( 18 ); AR( 19 ); AR( 20 ); AR( 21 ); AR( 22 ); AR( 23 );
}

void StagePropertiesDialog::reconcileLinks()
{
	foreach( Link * link, stage()->myLinks ){
		// make sure each link corresponds to an argument or another stage
		Node * from = link->fromNode();
		Node * to = link->toNode();
		Node * other;
		if( from == stage() ){
			other = to;
		}
		else{
			other = from;
		}
		bool ok = false;
		foreach( QString argumentName, stage()->arguments() ){
			if( 0 == argumentName.compare( other->name() ) ||
				other->typeOf() == "Stage" ){
				// to do verify the ioClass of this argument
				ok = true;
				break;
			}
		}//foreach
		if( !ok ){
			delete link;
		}
	}//foreach

	foreach( QString argumentName, stage()->arguments() ){
		bool ok = false;
		foreach( Link * link, stage()->myLinks ){
			Node * other;
			if( link->fromNode() == stage() ){
				other = link->toNode();
				// to do verify the ioClass is output or inout
			}
			else{
				other = link->fromNode();
				// to do verify the ioClass is input or inout
			}
			if( 0 == argumentName.compare( other->name() )){
				ok = true;
			}
		}//foreach
		if( !ok ){
			Node * otherNode = NULL;
			Uniforms::iterator uIt = stage()->window()->uniforms().find( argumentName );
			if( uIt != stage()->window()->uniforms().end() ){
				otherNode = uIt.value();
			}
			else{
				Buffers::iterator bIt = stage()->window()->buffers().find( argumentName );
				if( bIt != stage()->window()->buffers().end() ){
					otherNode = bIt.value();
				}
			}
			if( otherNode != NULL ){
				// create the link here,two links if inOut
				Kernel * kernel = stage()->kernel();
				int index;
				for( index = 1; index <= kernel->numParameters(); ++index ){
					if( stage()->arguments()[ index - 1 ].compare( argumentName ) == 0 ){
						break;
					}
				}//for
				if( kernel->ioClass()[ index ] == "input" ){
					stage()->window()->scene()->addItem( new Link( otherNode, stage() ));
				}
				else if( kernel->ioClass()[ index ] == "output" ){
					stage()->window()->scene()->addItem( new Link( stage(), otherNode ));
				}
				else if( kernel->ioClass()[ index ] == "inOut" ){
					stage()->window()->scene()->addItem( new Link( otherNode, stage() ));
					stage()->window()->scene()->addItem( new Link( stage(), otherNode ));
				}
			}
		}
	}//foreach
}

void StagePropertiesDialog::on_buttonBox_accepted()
{
	stage()->nameIs( name->text() );
	if( name->isModified() ){
		stage()->createTree();
	}
	stage()->typeIs( type->currentText() );
	stage()->selectorCountIs( selectorCount->value() );
	stage()->globalDimensionsIs( globalDimensions->value() );
	stage()->globalRangeIs( globalRange->text() );
	stage()->localDimensionsIs( localDimensions->value() );
	stage()->localRangeIs( localRange->text() );
	stage()->barrierIs( barrier->text() );
	if( type->currentText().compare( "kernel" ) == 0 ){
		QString kernelName = kernel->currentText();
		stage()->kernelNameIs( kernelName );
		Kernel * selectedKernel = stage()->window()->kernels().find( kernelName ).value();
		stage()->arguments().clear();
		for( int i = 1; i <= selectedKernel->numParameters(); ++i ){
			stage()->arguments().append( mArgument[ i - 1 ]->currentText() );
		}//for
		reconcileLinks();
	}
	else{
		stage()->kernelIs( NULL );
	}
	stage()->formatText();
    mStage->update();
    QDialog::accept();
}


